import os
import sys
import time


def renew_version():
    # 用法
    # build 版本号
    # 未传版本号参数时表示不更新版本号

    new_version = None if len(sys.argv) == 1 else sys.argv[1]
    if new_version is None:
        return

    print('Renewing version onto %r...' % new_version)

    root = os.path.dirname(__file__)
    meta_file = os.path.abspath(os.path.join(root, 'src/confio/__meta__.py'))

    try:
        with open(meta_file, mode='r', encoding='utf8') as fp:
            lines = fp.readlines()
        # 版本在第二行，可以写死
        version_line = lines[1].strip()
        version = version_line.split('=')[1].strip(' \'')
        print('The old version is %s' % version)
        [major, minor, build] = version.split('.')
        if new_version == 'auto':
            build = int(build) + 1
            new_version = '%s.%s.%s' % (major, minor, build)

        print('The new version is %r' % new_version)

        lines[1] = 'version = \'%s\'\n' % new_version
        lines[2] = 'version_info = (%s, %s, %s)\n' % (major, minor, build)

        with open(meta_file, mode='w', encoding='utf8') as fp:
            fp.writelines(lines)
        print('Renew version complete!\n')
        time.sleep(1)
    except Exception as e:
        print('Failure:' + str(e))
        exit(1)


if __name__ == '__main__':
    renew_version()
